package com.market.dao.jpa;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.market.dao.RoleDao;
import com.market.domain.Product;
import com.market.domain.Role;
import com.market.domain.User;

@Repository("roleDao")
public class RoleDaoJpa extends GenericDaoJpa<Role, Long> implements RoleDao {

	public RoleDaoJpa() {
		super(Role.class);
	}

	@Override
	public Role save(Role role) {
		Role savedRole = super.save(role);		
		String sql = "delete from user_role where roles_id = " + role.getId();
		Query query = this.em.createNativeQuery(sql);
		query.executeUpdate();
		if (role.getUsers().size() > 0) {
			for (User user : role.getUsers()) {
				sql = "insert into user_role (users_id, roles_id) value (";
				sql = sql + user.getId() + "," + role.getId() + ")";
				query = this.em.createNativeQuery(sql);
				query.executeUpdate();
			}
		}
		role.setId(savedRole.getId());//New role will return an id;
		return role;
	}

	public void remove(Role role) {
		if (this.findById(role.getId()) == null) {
			log.debug(this.getClass() + " Role with id " + role.getId()
					+ " not found, can not be deleted");
		} else {
			log.debug(this.getClass() + " Role with id " + role.getId()
					+ " found, will be deleted");
			super.removeById(role.getId());
		}

	}

	public List<User> findUsers(Role role) {
		String sql = "select user.* from user ,user_role  where user_role.users_id=user.id and user_role.roles_id = "
				+ role.getId();
		Query query = this.em.createNativeQuery(sql, User.class);
		List<User> users = query.getResultList();
		return users;
	}

}
